import subprocess
import platform
import os
from typing import List


def run_command(cmd_args: List[str]):
    """执行命令 ['python', '-m', 'pytest'] """
    print(f'运行的命令：{cmd_args}')
    if platform.system() == 'Linux':
        # 判断是linux系统
        print(f'判断是linux系统，执行。。。')
        p = subprocess.Popen(' '.join(cmd_args),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        # 输出stdout

        out, error = p.communicate()
        # a = p.wait()
        # out = p.stdout.read()
        res = out.decode('utf-8')
    else:
        # window 系统
        print(f'判断是 windows 系统，执行。。。')
        p = subprocess.Popen(cmd_args,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        # 输出stdout
        result = p.communicate()[0]
        try:
            res = result.decode('utf-8')
        except UnicodeDecodeError:
            res = result.decode('gb2312')
        except Exception as msg:
            print(msg)
            res = result
    return res


if __name__ == '__main__':
    res = run_command(['python', '-m', 'pytest'])
    print(res)